package com.hnl.action.attachment;

import java.io.IOException;
import java.io.Writer;
import java.util.Collection;
import java.util.Vector;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.LoggerFactory;

import com.hnl.core.aware.HNLTalentAware;
import com.hnl.dao.AttachmentDAO;
import com.hnl.dao.DAOException;
import com.hnl.dao.HNLDAOFactory;
import com.hnl.dao.MiscDAO;
import com.hnl.to.Attachment;
import com.hnl.to.Misc;
import com.hnl.to.wrapper.AttachmentWrapper;
import com.hnl.util.JSONResponseUtil;

@SuppressWarnings("serial")
public class LoadAttachment extends HttpServlet implements HNLTalentAware {
	public static final org.slf4j.Logger LOG = LoggerFactory
			.getLogger(LoadAttachment.class);

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		Writer writer = resp.getWriter();
		try {
			String talentID = req.getParameter(ATTRIBUTE_TALENT_ID);
			String attachmentType = req.getParameter("type");

			Collection<Attachment> docCollection = new Vector<Attachment>();
			if (talentID != null && talentID.length() != 0) {
				AttachmentDAO attachmentDAO = HNLDAOFactory.getDAOFactory(
						HNLDAOFactory.HNLDAOFACTORY).getAttachmentDAO();
				docCollection = attachmentDAO.loadAttachement(Integer
						.valueOf(talentID));
			}

			MiscDAO miscDAO = HNLDAOFactory.getDAOFactory(
					HNLDAOFactory.HNLDAOFACTORY).getMiscDAO();
			Collection<Misc> attachmentMisc = miscDAO
					.loadMiscByMiscTypeName("ATTACHMENT_TYPE");

			if (attachmentType != null && attachmentType.length() > 0) {
				Integer typeId = null;
				for (Misc misc : attachmentMisc) {
					if (misc.getMiscName().equals(attachmentType)) {
						typeId = misc.getMiscID();
					}
				}

				for (Attachment attachment : docCollection) {
					if (attachment.getAttachmentType().equals(typeId)) {
						AttachmentWrapper attachmentWrapper = new AttachmentWrapper(
								attachment);
						writer.write(JSONResponseUtil
								.getJSONObjectString(attachmentWrapper));
						break;
					}
				}
			} else {
				Collection<AttachmentWrapper> attachmentWrapperCollection = new Vector<AttachmentWrapper>();

				for (Attachment attachment : docCollection) {
					if (attachment.getAttachmentType().equals(
							Integer.valueOf(1))) {
						AttachmentWrapper attachmentWrapper = new AttachmentWrapper(
								attachment);
						attachmentWrapperCollection.add(attachmentWrapper);
					}
				}

				writer.write(JSONResponseUtil
						.getJSONObjectString(attachmentWrapperCollection));
			}

		} catch (DAOException e) {
			LOG.error("error laoding Talent", e);
		} finally {
			writer.close();
		}
	}
}
